package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.UserMapper;
import cn.tedu.weibo.pojo.dto.UserLoginDTO;
import cn.tedu.weibo.pojo.dto.UserRegDTO;
import cn.tedu.weibo.pojo.entity.User;
import cn.tedu.weibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
/**
 * @author 作者：HeShaoShuai
 * @Email 邮箱：2569819541@qq.com
 * @Date 日期：2023/5/17 9:44
 * @Package 包名：cn.tedu.weibo.controller
 * @Project 项目名：JavaSE
 * @Version 1.0
 */
@RestController
public class UserController {
	@Autowired(required = false)
	UserMapper mapper;
	@RequestMapping("/reg")
	public int reg(@RequestBody UserRegDTO userRegDTO){
		System.out.println("userRegDTO = " + userRegDTO);
		UserVO userVO = mapper.selectByUserName(userRegDTO.getUsername());
		if (userVO!=null){
			return 2;//代表用户名已存在!
		}
		User u = new User();
		BeanUtils.copyProperties(userRegDTO,u);//把dto里面已有的属性复制到实体类中
		u.setCreated(new Date());//给时间赋值
		mapper.insert(u);
		return 1;
	}

	@RequestMapping("/login")
	public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session){
		UserVO userVO = mapper.selectByUserName(userLoginDTO.getUsername());
		if (userVO!=null){
			if (userVO.getPassword().equals(userLoginDTO.getPassword())){
				//把登录成功的UserVO保存到 当前客户端对应的会话对象里面
				session.setAttribute("user",userVO);
				return 1;
			}
			return 2;
		}
		return 3;
	}
	@RequestMapping("/currentUser")
	public UserVO currentUser(HttpSession session){
		//从当前客户端对应的会话对象里面取出登录的UserVO
		UserVO user = (UserVO) session.getAttribute("user");
		//如果登陆过返回user对象 未登录返回null  但是经过JSON字符串转换后到客户端为空字符串
		return user;
	}
	@RequestMapping("/logout")
	public void logout(HttpSession session){
		session.removeAttribute("user");
	}
}